<template>
  <div v-loading="loading" class="rc-cont">
    <template v-if="titleShow">
      <div v-if="!isSeas" class="rc-head">
        <el-button icon="el-icon-plus" @click="createClick('title')">
          {{ $t('crm.components.a344aa933ba40947500ce5ac3b9849eb') }}
        </el-button>
      </div>
      <el-table :data="titleList" :height="tableHeight" stripe>
        <el-table-column
          v-for="(item, index) in titleFieldList"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="titleFieldFormatter"
          show-overflow-tooltip>
          <template slot-scope="{ row, column }">
            <wx-open-data
              v-if="item.formType == 'user'"
              :openid="row[column.property]" />
            <template
              v-else>
              {{ titleFieldFormatter(row, column) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('crm.components.3081d26b595282a7d04cd6268593d426')"
          width="100"
          fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary-text"
              style="padding: 0;"
              @click="handleTitle('edit', scope)">
              {{ $t('crm.components.02da5860dd103b03e58ab8d2e0937e90') }}
            </el-button>
            <el-button
              type="primary-text"
              style="padding: 0;"
              @click="handleTitle('delete', scope)">
              {{ $t('crm.components.2a23006ed4c079b3e9fc6464c1dca2ae') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <div class="rc-head margin-top-base2">
      <el-button
        v-if="!isSeas && invoiceSave"
        icon="el-icon-plus"
        @click="createClick('invoice')">
        {{ $t('crm.components.1f84a0cc624a1c9206bedb3c4bb34b0b') }}
      </el-button>
    </div>
    <el-table
      :data="invoiceList"
      :height="mainTableHeight"
      :cell-class-name="cellClassName"
      stripe
      @row-click="handleRowClick">
      <el-table-column
        v-for="(item, index) in fieldList"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        show-overflow-tooltip>
        <template slot-scope="{ row, column }">
          <template v-if="column.property == 'checkStatus'">
            <span
              :style="getStatusStyle(row.checkStatus)"
              class="status-mark" />
            <span>{{ getStatusName(row.checkStatus) }}</span>
          </template>
          <wx-open-data
            v-else-if="item.formType == 'user'"
            :openid="row[column.property]" />
          <template v-else>
            {{ invoicefieldFormatter(row, column) }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        v-if="invoiceUpdateInvoiceStatus"
        :resizable="false"
        :label="$t('crm.components.da9fafd1b931fdcf119101c89d204f9d')"
        fixed="right"
        width="100">
        <template slot-scope="scope">
          <el-button
            :disabled="scope.row.invoiceStatus == 1"
            type="primary-text"
            style="padding: 0;"
            @click="markReceivables(scope)">
            {{ scope.row.invoiceStatus == 1 ? $t('crm.components.6bbed9c836e06d67d70d75e6d7a5e70d'):$t('crm.components.edf82873152a0705eac590cf46248cd8') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <c-r-m-full-screen-detail
      :id="showFullId"
      :visible.sync="showFullDetail"
      crm-type="invoice"
      @handle="detailHandle" />
    <create
      v-if="isCreate"
      :action="createAction"
      @save-success="getInvoiceList"
      @close="isCreate=false" />
    <invoice-title-set
      :visible.sync="titleCreateShow"
      :customer-id="id"
      :detail="titleDetail"
      @change="getTitleList" />
    <mark-invoice
      :visible.sync="markShow"
      :detail="rowDetail"
      @change="getInvoiceList" />
  </div>
</template>

<script type="text/javascript">
import {
  crmCustomerInvoiceInfoAPI
} from '@/api/crm/customer'
import { crmInvoiceDeleteInvoiceInfoAPI } from '@/api/crm/invoice'
import { crmInvoiceIndexAPI } from '@/api/crm/invoice.js'

import CheckStatusMixin from '@/mixins/CheckStatusMixin'
import { separator } from '@/filters/vueNumeralFilter/filters'
import InvoiceTitleSet from '../invoice/components/InvoiceTitleSet'
import MarkInvoice from '../invoice/components/MarkInvoice'
import Create from '../invoice/Create'
import { mapGetters } from 'vuex'
import { getPermissionByKey } from '@/utils'
import crmTypeModel from '@/views/crm/model/crmTypeModel.js'

export default {
  name: 'RelativeInvoice', // 相关回访

  components: {
    Create,
    InvoiceTitleSet,
    MarkInvoice,
    CRMFullScreenDetail: () => import('@/components/CRMFullScreenDetail')
  },

  mixins: [CheckStatusMixin],

  inject: ['rootTabs'],

  props: {
    /** 模块ID */
    id: [String, Number],
    /** 没有值就是全部类型 有值就是当个类型 */
    crmType: {
      type: String,
      default: ''
    },
    /** 是公海 默认是客户 */
    isSeas: {
      type: Boolean,
      default: false
    },
    /** 客户和 合同下 可新建 抬头 */
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },

  data() {
    return {
      loading: false,
      invoiceList: [], // 发票列表
      fieldList: [],
      tableHeight: '250px',
      showFullDetail: false,
      showFullId: '', // 查看全屏详情的 ID
      createAction: null,
      isCreate: false, // 新建发票发票
      titleList: [],
      titleFieldList: [],

      titleCreateShow: false,
      titleDetail: null,

      rowDetail: {},
      markShow: false
    }
  },

  computed: {
    ...mapGetters(['crm']),
    // 发票title展示
    titleShow() {
      return this.crmType === 'customer'
    },

    // 发票列表高
    mainTableHeight() {
      return this.titleShow ? '250px' : '400px'
    },

    invoiceSave() {
      return !!getPermissionByKey('crm.invoice.save')
    },
    // 是否能操作
    invoiceUpdateInvoiceStatus() {
      return !!getPermissionByKey('crm.invoice.updateInvoiceStatus')
    }
  },

  watch: {
    id(val) {
      this.invoiceList = []
      this.titleList = []
      this.getInvoiceList()
      this.getTitleList()
    },

    'rootTabs.currentName'(val) {
      if (val === 'RelativeInvoice') {
        this.getInvoiceList(false)
        this.getTitleList(false)
      }
    }
  },

  mounted() {
    this.titleFieldList = [
      { prop: 'titleType', width: '120', label: this.$t('crm.components.49c0059cc9d9de38d45bc545651916a6') },
      { prop: 'invoiceTitle', width: '120', label: this.$t('crm.components.6b5caa07680836e32bee295b0db6af77') },
      { prop: 'taxNumber', width: '120', label: this.$t('crm.components.3e6628d60859bb2e2cd1becc3771e626') },
      { prop: 'depositBank', width: '120', label: this.$t('crm.components.20f302440f49a75fa0798adb07178e94') },
      { prop: 'depositAccount', width: '120', label: this.$t('crm.components.f7072292b28feec80727b6e93d2b4bdf') },
      { prop: 'depositAddress', width: '120', label: this.$t('crm.components.95e3a0b469ca636a0c72d23f14f9b702') },
      { prop: 'telephone', width: '120', label: this.$t('crm.components.774b3d35a54d00c76694c5b5b5f9da55') },
      { prop: 'ownerUserName', width: '120', label: this.$t('crm.components.0e9f3c5cf04112a00dccc7d252806928'), formType: 'user' },
      { prop: 'createTime', width: '120', label: this.$t('crm.components.4d526642bb873d21aea1d3abcd93896a') }
    ]

    this.getTitleList()

    const unit = `（${this.$unit('crm')}）`
    this.fieldList = [
      { prop: 'invoiceApplyNumber', width: '120', label: this.$t('crm.components.fa024d26804320ee3a70d160ec158ff1') },
      { prop: 'contractNum', width: '120', label: this.$t('crm.components.fc46c5d605a69c05af03be8f0a1346b5') },
      { prop: 'contractMoney', width: '120', label: '合同金额' + unit },
      { prop: 'invoiceMoney', width: '120', label: '开票金额' + unit },
      { prop: 'invoiceDate', width: '120', label: this.$t('crm.components.4bd6b2c97b74db35cc4bbe2855624d40') },
      { prop: 'realInvoiceDate', width: '120', label: this.$t('crm.components.ad9daddc80ec9692b8254c229b7077ba') },
      { prop: 'invoiceType', width: '120', label: this.$t('crm.components.266b234da7e3b461d1a79b7036ad5a8f') },
      { prop: 'invoiceNumber', width: '120', label: this.$t('crm.components.2550ecd152cc80634a48b398935cc359') },
      { prop: 'logisticsNumber', width: '120', label: this.$t('crm.components.e2ddb6b97becfbd453fcd1626e413483') },
      { prop: 'ownerUserName', width: '120', label: this.$t('crm.components.6e5d536f853617113ff0823122554ac4'), formType: 'user' },
      { prop: 'checkStatus', width: '120', label: this.$t('crm.components.ebd8e9c18b9b3d7e35fb358397ac77aa') }
    ]
    this.getInvoiceList()
  },

  methods: {
    /**
     * 抬头列表
     */
    getTitleList(loading = true) {
      if (this.titleShow) {
        this.loading = loading
        crmCustomerInvoiceInfoAPI({ customerId: this.id, pageType: 0 })
          .then(res => {
            this.loading = false
            this.titleList = res.data.list
          })
          .catch(() => {
            this.loading = false
          })
      }
    },

    /**
     * 发票列表
     */
    getInvoiceList(loading = true) {
      this.loading = loading
      const params = {
        pageType: 0,
        type: crmTypeModel[this.crmType],
        searchList: [
          {
            'type': 1,
            'values': [
              this.id
            ],
            'formType': 'text',
            'name': `${this.crmType}_id`
          }
        ]
      }
      crmInvoiceIndexAPI(params)
        .then(res => {
          this.loading = false
          const resData = res.data || {}
          this.invoiceList = resData.list || []
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
    /**
     * 当某一行被点击时会触发该事件
     */
    handleRowClick(row, column, event) {
      if (column.property == 'invoiceApplyNumber') {
        this.showFullId = row.invoiceId
        this.showFullDetail = true
      }
    },

    /**
     * 新建发票和抬头
     */
    createClick(type) {
      if (type == 'invoice') {
        if (this.crmType === 'customer') {
          this.createAction = { type: 'relative', crmType: this.crmType, data: {
            customer: this.detail,
            contactsName: this.detail.contactsName,
            contactsMobile: this.detail.contactsMobile,
            contactsAddress: this.detail.contactsAddress
          }}
        } else if (this.crmType === 'contract') {
          this.createAction = { type: 'relative', crmType: this.crmType, data: {
            customer: {
              customerName: this.detail.customerName,
              customerId: this.detail.customerId
            },
            contract: this.detail,
            contactsName: this.detail.contactsName,
            contactsMobile: this.detail.contactsMobile,
            contactsAddress: this.detail.contactsAddress
          }}
        }
        this.isCreate = true
      } else if (type == 'title') {
        this.titleDetail = null
        this.titleCreateShow = true
      }
    },

    /**
     * 编辑操作
     */
    handleTitle(type, item) {
      if (type == 'edit') {
        this.titleDetail = item.row
        this.titleCreateShow = true
      } else if (type == 'delete') {
        this.$confirm(
          this.$t('crm.components.a2e363acccce152101ebf337fe2ba8a3'),
          this.$t('crm.components.ee0a0439d197a6438a622f5659dbcbcd'),
          {
            confirmButtonText: this.$t('crm.components.44795d266079c2f30af21cfadd6d8545'),
            cancelButtonText: this.$t('crm.components.15c6a7ad8be1685dcdc8e0a89482c550'),
            type: 'warning'
          }
        )
          .then(() => {
            crmInvoiceDeleteInvoiceInfoAPI({
              infoId: item.row.infoId
            })
              .then(res => {
                this.titleList.splice(item.$index, 1)
                this.$message.success(this.$t('crm.components.19c2ebf3a6e6d531cdf03be8267b9d78'))
              })
              .catch(() => {})
          })
          .catch(() => {})
      }
    },

    /**
     * 发票格式化字段
     */
    invoicefieldFormatter(row, column) {
      if (column.property == 'contractMoney' || column.property == 'invoiceMoney') {
        return separator(this.$money('crm', row[column.property] || 0))
      }
      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    },

    /**
     * 抬头格式化字段
     */
    titleFieldFormatter(row, column) {
      if (column.property === 'titleType') {
        return {
          1: this.$t('crm.components.3f49b7ca3e01ecc8e32083ff09150d08'),
          2: this.$t('crm.components.0582d84afaac8569732b5048dd1768bb')
        }[row[column.property]]
      }
      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'invoiceApplyNumber') {
        return 'can-visit--underline'
      } else {
        return ''
      }
    },

    /**
     * @description: 状态颜色
     * @param {*} status
     * @return {*}
     */
    getStatusStyle(status) {
      return {
        backgroundColor: this.getStatusColor(status)
      }
    },

    /**
     * 详情操作
     */
    detailHandle(data) {
      if (data.type === 'delete') {
        this.getInvoiceList()
        this.$nextTick(() => {
          this.$bus.emit('crm-tab-num-update')
        })
      } else {
        this.getInvoiceList()
      }
    },

    /**
     * 开票操作
     */
    markReceivables(scope) {
      this.rowDetail = scope.row
      this.markShow = true
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/relativecrm.scss";
@import "../styles/table.scss";
</style>
